package controllers

import (
	"io/ioutil"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/globalsign/mgo/bson"

	"cmt1-admin/lib/request"
	"cmt1-admin/models"
)

type UserPetQuery struct {
	BaseRequest
	Name string `form:"name"`
}

//转发请求，修改用户宠物的信息
func SetUserPetInfo(c *gin.Context) {
	data, _ := ioutil.ReadAll(c.Request.Body)
	//转发请求，请求游戏服务器
	res, err := request.PostByte("userPet/modify", data)
	if err != nil {
		handleErr(c, 401, err.Error())
		return
	}
	c.Writer.Header().Set("content-type", "application/json")
	c.String(http.StatusOK, string(res))
}

//转发请求，通过用户uid查看用户宠物信息
func GetUserPetInfoByUid(c *gin.Context) {
	uid := c.Param("uid")
	//转发请求，请求游戏服务器
	res, err := request.Get("userPet/info/" + uid)
	if err != nil {
		handleErr(c, 401, err.Error())
		return
	}
	c.Writer.Header().Set("content-type", "application/json")
	c.String(http.StatusOK, string(res))
}

//访问数据库，通过用户uid查看用户宠物信息
func UserPetInfoByUid(c *gin.Context) {
	uid := c.Param("uid")
	userPet := new(models.UserPet)
	err := GameDB.FindOne("userPet", bson.M{"_id": bson.ObjectIdHex(uid)}, nil, &userPet)
	if err != nil {
		handleErr(c, 404, err.Error())
		return
	}
	handleOk(c, map[string]interface{}{"userPet": userPet})
}

//获取所有用户宠物信息
func GetUserPetList(c *gin.Context) {
	userPetQuery := &UserPetQuery{}
	if err := c.ShouldBindQuery(&userPetQuery); err != nil {
		handleErr(c, 404, err.Error())
		return
	}
	if userPetQuery.Page > 0 {
		userPetQuery.Page -= 1
	}

	mquery := make(map[string]interface{}, 0)
	count, err := GameDB.Count("userPet", mquery)
	if err != nil {
		handleErr(c, 404, err.Error())
		return
	}
	userPets := make([]*models.UserPet, 0)
	err = GameDB.FindPage("userPet", userPetQuery.Page, userPetQuery.PageNum, mquery, nil, &userPets)
	if err != nil {
		handleErr(c, 404, err.Error())
		return
	}
	handleOk(c, map[string]interface{}{"userPets": userPets, "count": count})
}
